<template>
  <div class="header-tool">
    <a-input-search
      class="mr10"
      style="width: 200px"
      v-model:value="user_name"
      placeholder="请输入用户名"
      @search="onSearch"
    />
    <a-input-search
      class="mr10"
      style="width: 200px"
      type="number"
      @search="onSearch"
      v-model:value="pagination.user_phone"
      placeholder="请输入手机号"
    />
    <a-button
      class="mr10"
      type="primary"
      @click="reLoad()"
    >
      搜索
    </a-button>
    <a-button
      class="mr10"
      type="primary"
      @click="reLoad()"
    >
      刷新
    </a-button>

    <a-button
      class="mr10"
      :disabled="mapRows.length == 0"
      type="primary"
      @click="batchSendSms()"
    >
      批量发送短信
    </a-button>
  </div>

  <a-table
    :row-key="(record) => record.uid"
    :loading="loading"
    :rowSelection="{
      onChange: onSelectChange,
      selectedRows: selectedRows,
      selectedRowKeys: mapRows
    }"
    :columns="columns"
    :dataSource="activities"
    @change="handleTableChange"
    :pagination="
      isObject(pagination)
        ? {
            showQuickJumper: true,
            total: pagination.total,
            current: pagination.current,
            pageSize: pagination.pageSize,
            showTotal: (total) => `共计 ${pagination.total} 条`
          }
        : false
    "
  >
    <!-- <template #expandIcon="row">
    <UpOutlined  v-if="row.expanded" @click="getRows(row, $event)" />
      <DownOutlined v-else @click="getRows(row, $event)" />
   
      </template> -->

    <template #expandedRowRender="{ record }">
      <div
        style="margin-left: 80px"
        class="user-info-detail"
      >
        <p>出生日期：{{ record?.IdCard?.birthday }}</p>
        <p v-if="record?.IdCard?.birthday">年龄：{{ computedAge(record?.IdCard?.birthday) }}</p>
        <p v-else>年龄：</p>
        <p>性别：{{ record?.IdCard?.sex }}</p>
        <p>邮箱：{{ record.email }}</p>
        <p>所在地：{{ record.area }}</p>
        <p>创建时间：{{ record.created_at }}</p>
      </div>
    </template>
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'avatar'">
        <div
          class="user-info"
          @click="handleEdit(record)"
        >
          <img
            class="user-info-avatar"
            :src="record.avatar"
            alt=""
          />
          <div class="user-name">
            <div class="name">{{ record.user_name }}</div>
            <div class="phone">{{ record.phone }}</div>
            <a>编辑</a>
          </div>
        </div>
      </template>

      <template v-if="column.dataIndex === 'power'">
        <a-dropdown>
          <a
            class="ant-dropdown-link"
            @click.prevent
          >
            <a-tag
              color="cyan"
              v-if="record.power == 1"
            >
              普通用户
            </a-tag>
            <a-tag
              color="blue"
              v-if="record.power == 7"
            >
              销售
            </a-tag>
            <a-tag
              color="orange"
              v-if="record.power == 16"
            >
              核销员
            </a-tag>
            <DownOutlined   v-if="getPower(32)"/>
          </a>
          <template #overlay   v-if="getPower(32)">
            <a-menu @click="setSells($event, record)">
              <a-menu-item
                key="1"
                v-if="record.power != 1"
              >
                设为普通用户
              </a-menu-item>

              <a-menu-item
                key="7"
                v-if="record.power != 7"
              >
                设为销售
              </a-menu-item>
              <a-menu-item
                key="16"
                v-if="record.power != 16"
              >
                设为核销员
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>

        <!-- <a
          v-if="record.power == 1"
          @click="setSells(record)"
        >
          设为销售
        </a> -->
      </template>

      <template v-if="column.dataIndex === 'point'">
        {{ record.point }}
        <a @click="handleIntegral(record)">修改</a>
      </template>
      <template v-if="column.dataIndex === 'status'">
        <a-tag
          color="success"
          v-if="record.status == 'active'"
        >
          正常
        </a-tag>

        <a-tag
          color="error"
          v-else
        >
          异常
        </a-tag>
        <br />
      </template>

      <template v-if="column.dataIndex === 'action'">
        <span>
          <a @click="handleRebate(record)">查返佣</a>
          <br />

          <a @click="handleRebateLog(record)">查结算记录</a>

          <br />

          <a @click="sendMsg(record)">发短信</a>
        </span>
      </template>
    </template>
  </a-table>

  <smsModel
    ref="sendEle"
    @sendOk="sendOk"
  />
  <userForm
    ref="userEle"
    @success="updateSuccess"
  />
  <!-- 返佣 -->
  <rebateList ref="rebateEle"></rebateList>
  <!-- 结算记录 -->
  <rebateLog ref="rebateLogEle"></rebateLog>
</template>

<script setup>
  import { UpOutlined, DownOutlined } from '@ant-design/icons-vue'

import { getPower } from '@/utils/power'
  import rebateLog from './rebateLog.vue'
  import rebateList from './rebateList.vue'
  import { isObject } from 'lodash-es'
  import smsModel from './smsModel.vue'
  import { message } from 'ant-design-vue'
  import { getUserlist, userRecordUpdate, userUpdate } from '@/api/index'
  import userForm from './userForm.vue'
  import { ref, reactive, onMounted, computed } from 'vue'
  import { useRouter } from 'vue-router'
  const router = useRouter()
  const activities = ref([])
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    user_phone: ''
  })
  const loading = ref(false)
  const Integralpagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const getRows = (props, event) => {
    // console.log(props)
    props.onExpand(props.record, event)
  }
  const rebateEle = ref(null)
  const userEle = ref(null)

  const visible = ref(false)
  const selectUser = ref({})
  const columns = [
    // {
    //   title: 'ID',
    //   dataIndex: 'uid'
    // },
    {
      title: '基本信息',
      dataIndex: 'avatar',
      width: '300px'
    },
    // {
    //   title: '昵称',
    //   dataIndex: 'user_name'
    // },
    // {
    //   title: '手机号',
    //   dataIndex: 'phone'
    // },
    {
      title: '积分',
      dataIndex: 'point',
      width: '80px'
    },
    {
      title: '用户等级',
      dataIndex: 'power',
      width: '200px'
    },
    {
      title: '状态',
      dataIndex: 'status'
    },

    {
      title: '邀请码',
      dataIndex: 'inviteCode'
    },
    // {
    //   title: '邮箱',
    //   dataIndex: 'email'
    // },
    // {
    //   title: '所在地',
    //   dataIndex: 'area'
    // },

    {
      title: '最近登录',
      dataIndex: 'login_at',
      width: '120px'
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: '200px'
    }
  ]

  const mapRows = ref([])
  const selectedRows = ref([])

  const selects = ref([])
  const onSelectChange = (selectedRowKeys, selectedRows) => {
    mapRows.value = selectedRowKeys
    selects.value = selectedRows
  }

  const sendEle = ref(null)
  const sendMsg = (record) => {
    sendEle.value.init(0, record)
  }
  const setSells = (event, row) => {
    userUpdate({
      uid: row.uid,
      power: Number(event.key)
    })
      .then((res) => {
        if (res.errorCode) {
          return message.warn(res.msg)
        }
        message.success('设置成功')
        getList()
      })
      .catch((err) => {
        message.error(err.msg)
      })
  }
  const IntegralhandleTableChange = ({ current, pageSize }) => {
    Integralpagination.current = current
    Integralpagination.pageSize = pageSize
  }
  const rebateLogEle = ref(null)
  const handleRebateLog = (row) => {
    rebateLogEle.value.init(row)
  }
  const handleRebate = (row) => {
    rebateEle.value.init(row)
  }

  const batchSendSms = () => {
    sendEle.value.init(1, selects.value)
  }
  const computedAge = (date) => {
    const birthDate = new Date(date)
    const today = new Date()
    let age = today.getFullYear() - birthDate.getFullYear()
    const m = today.getMonth() - birthDate.getMonth()
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
      age--
    }
    return age
  }
  const user_name = ref('')
  const getList = () => {
    loading.value = true
    getUserlist({
      user_name: user_name.value,
      page: pagination.current,
      phone: pagination.user_phone == null ? '' : pagination.user_phone,
      pageSize: pagination.pageSize,
      login_at: true
    })
      .then((res) => {
        if (res.errorCode) {
          message.error(res.msg || '操作失败')
          return
        }
        activities.value = res.data
        pagination.total = res.total
      })
      .catch((err) => {
        message.error(err.msg)
      })
      .finally(() => {
        loading.value = false
      })
  }
  const handleTableChange = ({ current, pageSize }) => {
    pagination.current = current
    pagination.pageSize = pageSize
    getList()
  }
  const sendOk = () => {
    getList()
  }
  const updateSuccess = () => {
    getList()
  }
  const reLoad = () => {
    pagination.current = 1
    getList()
  }
  const handleIntegral = (row) => {
    router.push({
      path: '/user/record',
      query: {
        id: row.uid
      }
    })

    visible.value = true
    selectUser.value = row
  }

  const handleEdit = (row) => {
    userEle.value.init(row)
  }

  onMounted(() => {
    getList()
  })
</script>
<style scoped lang="less">
  .header-tool {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 10px;
  }
  .mr10 {
    margin-right: 10px;
  }
  .user-info {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    .user-info-avatar {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      margin-right: 10px;
    }
  }
  .user-info-detail {
    margin-left: 80px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    p {
      margin-right: 30px;
      width: 300px;
    }
  }
</style>
